//【习10.1】 基于Socket通信的裁判评分。
//裁判员  
package org.langqiao.network.judge;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class UmpireJFrame extends JFrame implements ActionListener
{
    private JTextField text_name,text_score;               //接收选手名和输入得分的文本行
    private JButton button;                                //发送按钮
    private DataOutputStream dout;                         //数据字节输出流
    
    public UmpireJFrame(String name, String host, int port) throws IOException 
    {                        //name指定裁判员名，host、port指定服务端主机和端口
        super("裁判员 "+name);
        this.setBounds(650,300,400,100);
        this.setBackground(Color.lightGray);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        JPanel panel = new JPanel();
        this.getContentPane().add(panel);
        panel.add(new JLabel("选手名"));
        text_name = new JTextField("",10);
        text_name.setEditable(false);
        panel.add(text_name);
        panel.add(new JLabel("得分"));
        text_score = new JTextField("",10);
        text_score.setHorizontalAlignment(JTextField.CENTER);
        panel.add(text_score);
        button=new JButton("发送");
        panel.add(button);
        button.setEnabled(false);
        button.addActionListener(this);
        this.setVisible(true);

        Socket socket = new Socket(host, port);            //客户端请求TCP连接
        PrintWriter pout=new PrintWriter(socket.getOutputStream(),true);//获得Socket输出流，立即flush
        pout.println(name);                             //发送裁判员名给服务端
        dout=new DataOutputStream(socket.getOutputStream());//由Socket输出流创建数据字节输出流
        BufferedReader cin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line="";
        while ((line=cin.readLine())!=null)
        {
            this.text_name.setText(line);
            this.text_score.setText("");
            button.setEnabled(true);
        }
        text_name.setText("");
        text_score.setText("");
        button.setEnabled(false);
        text_score.setEditable(false);
        cin.close();
        dout.close();
        pout.close();
        socket.close();
    }

    public void actionPerformed(ActionEvent e)             //单击事件处理方法
    {
        try
        {
             double x=Double.parseDouble(text_score.getText());
             this.dout.writeDouble(x);                     //发送分值
             System.out.println("send "+x);
             button.setEnabled(false);
        }
        catch(NumberFormatException nfe)
        {
            JOptionPane.showMessageDialog(this,"\""+text_score.getText()+"\"不能转换成数值，请重新输入!");
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
     
    public static void main(String arg[]) throws IOException
    {
        new UmpireJFrame("王汉强","127.0.0.1", 2010);
    }
}